const { ipcMain } = require("electron");
const robotjs = require("robotjs");
const vkey = require("vkey");

function handlerMouse(data) {
  // data:{clientX,clientY,screen:{width,heigth},video:{width,height}}
  const { clientX, clientY, screen, video } = data;
  let x = (clientX * screen.width) / video.width;
  let y = (clientY * screen.height) / video.height;
  console.log(x, y);

  robotjs.moveMouse(x, y);
  // robotjs.moveMouse(200, 200);
  robotjs.mouseClick();
}

function handlerKey(data) {
  // data:{keyCode,meta,alt,ctrl,shift,win}
  const { keyCode, meta, alt, ctrl, shift, win } = data;
  const modifiers = [];
  if (meta) modifiers.push("meta");
  if (alt) modifiers.push("alt");
  if (ctrl) modifiers.push("control");
  if (shift) modifiers.push("shift");
  if (win) modifiers.push("win");
  const key = vkey[keyCode].toLowerCase(); // 按键转换，将keyCode转换为按键名称
  if (key[0] != "<") {
    //判断是否是特殊按键<>，如<enter>
    robotjs.keyTap(key, modifiers);
  }
}

module.exports = () => {
  ipcMain.on("robot", (event, type, data) => {
    if (type === "mouse") {
      handlerMouse(data);
    } else if (type === "key") {
      handlerKey(data);
    }
  });
};
